<template>
	<view class="flex">
		<view @click.stop="sub" class="font-md bg-light text-muted text-center flex justify-center align-center"
			style="width: 50rpx;height: 50rpx;">-</view>
		<view @input="handleParentInput" class="flex bg-light border-left border-right justify-center align-center font"
			style="width: 50rpx;height: 50rpx;">
			<input @change.stop="change" @click.stop="handleParentInput" v-model="Quantity" type="number" class="w-100 text-center" />
		</view>
		<view @click.stop="add" class="font-md bg-light text-muted text-center flex justify-center align-center"
			style="width: 50rpx;height: 50rpx;">+</view>
	</view>
</template>

<script>
	export default {
		name:"counter",
		data() {
			return {
				Quantity: this.value
			}
		},
		props: {
			value: {
				type: Number,
				default: 1
			},
			max: {
				type: Number,
				default: 0
			},
			loading: {
				type: Boolean,
				default: false
			}
		},
		watch: {
			value(newVal) {
			    this.Quantity = newVal
			},
			Quantity(newVal) {
			    this.$emit('input', newVal);
			}
		},
		methods: {
			handleParentInput(event){
				event.stopPropagation();
			},
			add() { //添加
				if (!this.loading) {
					if (this.max == 0) {
						this.Quantity++
					} else {
						if (this.Quantity * 1 < this.max * 1) {
							this.Quantity++
						} else {
							uni.showToast({
								title: '已经最大值了!',
								icon: 'none'
							})
						}
					}
					this.$emit('change',this.Quantity);
				}
			},
			sub() { //减
				if (!this.loading) {
					if (this.Quantity > 1) {
						this.Quantity--;
						this.$emit('change',this.Quantity);
					} else {
						// uni.showToast({
						// 	title: "至少选择一件商品！",
						// 	icon: "none",
						// });
						this.$emit('remove')
					}
				}
			},
			change() { //查询
				//判断是否为数字
				if (!isNaN(parseFloat(this.Quantity)) && isFinite(this.Quantity)) {
					if (this.max > 0 && parseInt(this.Quantity) > parseInt(this.max)) {
						this.Quantity = this.max
					}
				} else {
					this.Quantity = 1
				}
				this.$emit('change',this.Quantity);
			}
		}
	}
</script>

<style>

</style>